package cn.devices.controller;


import cn.devices.TbDmDto;
import cn.devices.dto.DmUserDto;
import cn.devices.entity.TbDm;
import cn.devices.entity.TbUser;
import cn.devices.model.JsonMessage;
import cn.devices.security.AuthUserDetail;
import cn.devices.service.TbCodeGenService;
import cn.devices.service.TbUserService;
import cn.devices.utils.FileUtil;
import cn.devices.utils.SubjectType;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.FileUtils;
import org.apache.tomcat.util.net.openssl.ciphers.Authentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 员工表 前端控制器
 * </p>
 * 1.添加员工：tbUserAdd  部门号必加
 * 2.更新：tbUserUpdate
 * 3.员工个人信息：tbUserGetById
 * 4.所有员工：tbUserList 按部门查询时depName传入数据
 * 5.删除：tbUserDeleteFalse 假删除 tbUserDeleteTrue 真删除
 *
 * @author 秋水浮萍
 * @since 2021-02-07
 */
@RestController
@RequestMapping("/tb-user")
public class TbUserController {

    @Value("${load.upload}")
    private String uploadPath;


    @Autowired
    private TbUserService tbUserService;

    @Autowired
    private TbCodeGenService genService;

//
//    @GetMapping("imgInfo")
//    public JsonMessage imgInfo(String path) {
//        JsonMessage message = new JsonMessage();
//        File file = new File(path);
//        if (file.exists()) {
//            try {
//                byte[] imgBytes = FileUtils.readFileToByteArray(file);
//                message.setData(imgBytes);
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            } catch (Exception e) {
//                e.printStackTrace();
//
//            }
//        }
//        return message;
//    }

//    @GetMapping(value = "/file/{fileName}")
//    public ResponseEntity<FileSystemResource> getFile(String fileName) throws FileNotFoundException {
//        File file = new File(filePath, fileName);
//        if (file.exists()) {
//            return export(file);
//        }
//        System.out.println(file);
//        return null;
//    }
//
//
//    public ResponseEntity<FileSystemResource> export(File file) {
//        if (file == null) {
//            return null;
//        }
//        HttpHeaders headers = new HttpHeaders();
//        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
//        headers.add("Content-Disposition", "attachment; filename=" + file.getName());
//        headers.add("Pragma", "no-cache");
//        headers.add("Expires", "0");
//        headers.add("Last-Modified", new Date().toString());
//        headers.add("ETag", String.valueOf(System.currentTimeMillis()));
//        return ResponseEntity.ok().headers(headers).contentLength(file.length()).contentType(MediaType.parseMediaType("application/octet-stream")).body(new FileSystemResource(file));
//    }

    @GetMapping(value = "imgInfo",produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] imgInfo(String path) throws Exception {
        byte[] bs=null;
        File file = new File(path);
        if (file.exists()) {
            FileInputStream inputStream = new FileInputStream(file);
             bs = new byte[inputStream.available()];
            inputStream.read(bs, 0, inputStream.available());
            return bs;
        }
        return bs;
    }



//    @RequestMapping(value = "imgInfo", produces = MediaType.IMAGE_PNG_VALUE)
//    public ResponseEntity<byte[]> imgInfo(String path) throws Exception {
//
//        byte[] imageContent;
//        imageContent = fileToByte(new File(path));
//
//        final HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.IMAGE_PNG);
//        return new ResponseEntity<>(imageContent, headers, HttpStatus.OK);
//    }
//
//    public static byte[] fileToByte(File img) throws Exception {
//        byte[] bytes = null;
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        try {
//            BufferedImage bi;
//            bi = ImageIO.read(img);
//            ImageIO.write(bi, "jpg", baos);
//            bytes = baos.toByteArray();
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            baos.close();
//        }
//        return bytes;
//    }




    @GetMapping("androidUserDto")
    public JsonMessage androidUserDto() {
        JsonMessage message = new JsonMessage();
        message.setData(tbUserService.androidUserDtos());
        return message;
    }


    /**
     * 部门  人员
     *
     * @return
     */
    @GetMapping("dmUserDtoList")
    public JsonMessage dmUserDtoList() {
        JsonMessage message = new JsonMessage();
        List<DmUserDto> list = tbUserService.dmUserDtoList();
        message.setData(list);
        return message;
    }

    @PostMapping("tbUserImg")
    public JsonMessage tbUserImg(@RequestParam("file") MultipartFile file) {
        JsonMessage message = new JsonMessage();
        UUID randomUUID = UUID.randomUUID();
        String a = "";
        // 获取原始名字
        String fileName = file.getOriginalFilename();
        // 获取后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 文件保存路径
        String path = uploadPath + File.separator + "user";
        String filePath = path + File.separator + randomUUID + suffixName;

        // 文件对象
        File dest = new File(filePath);
        // 判断路径是否存在，如果不存在则创建
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            // 保存到服务器中
            file.transferTo(dest);
            message.setData(filePath);
            return message;
        } catch (Exception e) {
            e.printStackTrace();
            message.setData("上传失败");
        }
        return message;
    }

    /**
     * 添加员工信息
     *
     * @param tbUser
     * @return
     */
    @PostMapping("tbUserAdd")
    public JsonMessage tbUserAdd(@RequestBody TbUser tbUser) throws IOException {
        JsonMessage message = new JsonMessage();
        tbUser.setUserId(genService.genCode(SubjectType.USER));
        if (tbUserService.countTel(tbUser.getTelephone(), tbUser.getUserId()) > 0) {
            message.setData(1);
            return message;
        }
        FileUtil u = new FileUtil();
        String newPath = u.FixFileName(tbUser.getUserPhoto(), tbUser.getUserId());
        tbUser.setUserPhoto(newPath);
        tbUserService.tbUserAdd(tbUser);
        message.setData("添加成功");
        return message;

    }

    /**
     * 更新
     *
     * @param tbUser
     * @return
     */
    @PostMapping("tbUserUpdate")
    public JsonMessage tbUserUpdate(@RequestBody TbUser tbUser) {
        JsonMessage message = new JsonMessage();
        String a="";
        if (tbUserService.countTel(tbUser.getTelephone(), tbUser.getUserId()) > 0) {
            message.setData(1);
            return message;
        }
        tbUserService.tbUserUpdate(tbUser);
        message.setData("更新成功");
        return message;
    }

    /**
     * 根据id 查询员工个人信息
     *
     * @param userId
     * @return
     */
    @GetMapping("tbUserGetById")
    public JsonMessage tbUserGetById(String userId) {
        JsonMessage message = new JsonMessage();
        message.setData(tbUserService.userGetById(userId));
        return message;
    }

    @GetMapping("tbUserList")
    public JsonMessage tbUserList(@RequestParam(defaultValue = "1") int pageIndex,
                                  @RequestParam(defaultValue = "10") int pageSize,
                                  String depName) {
        JsonMessage message = new JsonMessage();
        PageInfo<TbUser> list = tbUserService.tbUserList(pageIndex, pageSize, depName);
        message.setData(list);
        return message;
    }


    @GetMapping("tbUserDeleteFalse")
    public JsonMessage tbUserDeleteFalse(String userId) {
        JsonMessage message = new JsonMessage();
        tbUserService.tbUserDeleteFalse(userId);
        message.setData("删除成功");
        return message;
    }

    @GetMapping("tbUserDeleteTrue")
    public JsonMessage tbUserDeleteTrue(String userId) {
        JsonMessage message = new JsonMessage();
        tbUserService.tbUserDeleteTrue(userId);
        message.setData("删除成功");
        return message;
    }

}
